package io.renren.modules.weixin.Service.impl;

import io.renren.modules.weixin.Service.*;
import io.renren.modules.weixin.Util.WeixinUtil;
import io.renren.modules.weixin.entity.AccessToken;
import io.renren.modules.weixin.entity.WxBindEntity;
import io.renren.modules.weixin.entity.ZbAdminEntity;
import io.renren.modules.weixin.entity.ZbResultEntity;
import io.renren.modules.weixin.message.sendSelect.*;
import io.renren.modules.weixin.message.senderror.*;
import io.renren.modules.weixin.message.senderror.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author: Mr-wang
 * @date: 2018/4/23 0023 16:09
 * @Description:
 */
@Service("weixinService")
public class WeixinServiceImpl implements WeixinService {
    @Value("${static.url}")
    private String staticUrl;
    @Autowired
    private AccessTokenService accessTokenService;
    @Autowired
    private ZbAdminService zbAdminService;
    @Autowired
    private ZbResultService zbResultService;
    @Autowired
    private WxBindService wxBindService;

    @Override
    public String getToken() {
        // 第三方用户唯一凭证
        String appId = "wx19490b405bf5ada2";
        // 第三方用户唯一凭证密钥
        String appSecret = "8c6095d9fd0335c21f5a3f56f2b846cd";
        String token = null;
        AccessToken ac = accessTokenService.selectById(202);
        if( ac == null ){
            // 调用接口获取access_token
            AccessToken at = WeixinUtil.getAccessToken(appId, appSecret);
            token = at.getToken();
            at.setExpiresIn(new Date());
            accessTokenService.insert(at);
            System.out.println("first insert token");
        }else if( 7100 <=(new Date().getTime() - ac.getExpiresIn().getTime())/1000){
            //delete old token
            accessTokenService.deleteById(202);

            // 调用接口获取access_token
            AccessToken at = WeixinUtil.getAccessToken(appId, appSecret);
            token = at.getToken();
            at.setExpiresIn(new Date());
            accessTokenService.insert(at);
            System.out.println("delete old token");
        }else {
            token = ac.getToken();
            System.out.println("get token");
        }
        return token;
    }

    public final static String send_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
    public final static String warningInfo = "zxKJERGe543l0UW5JXcAUDmwMqvPkZM_VY14b4lpcJc";
    public final static String alertInfo = "bI1OXKEpjsxOFkuGv2giVbX6By-9oS8cF8arpL-qA1Y";
    public final static String errorInfo = "jRV6lxVaSSuMHAJDp6Uy4TqYq7KLa1HsZ8smzcohp98";
    @Override
    public void senderror(Date opt, ZbResultEntity zbR) {
        List<ZbAdminEntity> zbAdmin = zbAdminService.selectByzbCode(zbR.getZbCode());
        if(zbAdmin.size() == 0){
            zbResultService.insert(zbR);
        }else {
            for (ZbAdminEntity zbA : zbAdmin) {
                double minerror = zbA.getZbMinValue() - (zbA.getMinValue() - zbA.getZbMinValue());
                double maxerror = zbA.getZbMaxValue() + (zbA.getZbMaxValue() - zbA.getMaxValue());
                double zbRValue = zbR.getZbValue();
                if ((zbRValue <= zbA.getMinValue() && zbRValue >= zbA.getZbMinValue()) || (zbRValue >= zbA.getMaxValue() && zbRValue <= zbA.getZbMaxValue())) {
                    zbR.setDqState("warning");
                    System.out.println("蓝色预警");
                    String creator = zbA.getCreator();
                    String zbcode = zbA.getZbCode();
                    int warning = zbA.getWarning() + 1;
                    zbAdminService.updateOkByzbCodeAndcreater(warning, zbcode, creator);
                    zbResultService.insert(zbR);
                    Senderror s = getSenderror(opt, zbA, zbR, warningInfo);
                    WeixinUtil.createTemplate(send_url, "错误信息", s, getToken());
                } else if ((zbRValue <= zbA.getZbMinValue() && zbRValue >= minerror) || (zbRValue >= zbA.getZbMaxValue() && zbRValue <= maxerror)) {
                    zbR.setDqState("alert");
                    System.out.println("橙色预警");
                    String creator = zbA.getCreator();
                    String zbcode = zbA.getZbCode();
                    int alert = zbA.getAlert() + 1;
                    zbAdminService.updateAlertByzbCodeAndcreater(alert, zbcode, creator);
                    zbResultService.insert(zbR);
                    Senderror s = getSenderror(opt, zbA, zbR, alertInfo);
                    WeixinUtil.createTemplate(send_url, "错误信息", s, getToken());
                } else if ((zbRValue < minerror) || (zbRValue > maxerror)) {
                    zbR.setDqState("error");
                    System.out.println("红色预警");
                    String creator = zbA.getCreator();
                    String zbcode = zbA.getZbCode();
                    int error = zbA.getError() + 1;
                    zbAdminService.updateErrorByzbCodeAndcreater(error, zbcode, creator);
                    zbResultService.insert(zbR);
                    Senderror s = getSenderror(opt, zbA, zbR, errorInfo);
                    WeixinUtil.createTemplate(send_url, "错误信息", s, getToken());
                } else {
                    System.out.println("预警处理");
                    zbR.setDqState("ok");
                    String creator = zbA.getCreator();
                    String zbcode = zbA.getZbCode();
                    int ok = zbA.getOk() + 1;
                    zbAdminService.updateOkByzbCodeAndcreater(ok, zbcode, creator);
                    zbResultService.insert(zbR);
                }
            }
        }
    }

    @Override
    public int quickSelect(String from_name) {
       WxBindEntity wbind = wxBindService.selectByFormName(from_name);
       String user = wbind.getAdminName();
       List<ZbAdminEntity> zbAdmin = zbAdminService.selectBycreator(user);
       if(zbAdmin.size() == 0){
           return 1;
       }else {
           for(ZbAdminEntity zbA : zbAdmin){
               if(zbA.getZbLevel().equals("实时可查")){
                   SendSelect s = getSendSelect(zbA);
                   WeixinUtil.createTemplate(send_url, "一键查询", s, getToken());
               }
           }
           return 0;
       }
    }

    public SendSelect getSendSelect(ZbAdminEntity zbA){
        ZbCode zbc = new ZbCode();
        zbc.setValue(zbA.getZbCode());
        zbc.setColor("#ccccccc");

        ZbName zbn = new ZbName();
        zbn.setValue(zbA.getZbName());
        zbn.setColor("#cccccc");

        ZbAvg avg = new ZbAvg();
        avg.setColor("#888888");
        avg.setValue(zbA.getZbAvgValue());

        ZbLate late = new ZbLate();
        late.setColor("#888888");
        late.setValue(zbA.getZbLateValue());

        ZbMin min = new ZbMin();
        min.setColor("#888888");
        min.setValue(zbA.getZbMinValue());

        ZbMax max = new ZbMax();
        max.setColor("#888888");
        max.setValue(zbA.getZbMaxValue());

        ZbWarning warning = new ZbWarning();
        warning.setColor("#888888");
        warning.setValue(zbA.getWarning());

        ZbAlert alert = new ZbAlert();
        alert.setColor("#888888");
        alert.setValue(zbA.getAlert());

        ZbError error = new ZbError();
        error.setColor("#888888");
        error.setValue(zbA.getError());

        DataSelect data = new DataSelect();
        data.setZbCode(zbc);
        data.setZbName(zbn);
        data.setZbLate(late);
        data.setZbMax(max);
        data.setZbMin(min);
        data.setZbAvg(avg);
        data.setZbAlert(alert);
        data.setZbWarning(warning);
        data.setZbError(error);

        SendSelect sends = new SendSelect();
        String touser = wxBindService.selectByAdminName(zbA.getCreator()).getFromName();
        sends.setTouser(touser);
        sends.setTemplate_id("4_0_7ATQsD7ik1j8pNI3vntP8G_RJ2SbVlHzT3ZLAlU");
        sends.setUrl(staticUrl+"/wechat/phone/index.html?zbcode="+zbA.getZbCode()+"&creator="+zbA.getCreator());
        sends.setTopcolor("#cccccc");
        sends.setData(data);
       return sends;
    };

    public Senderror getSenderror(Date OPT, ZbAdminEntity z, ZbResultEntity zbResultEntity, String info){
        Zbcode zbc = new Zbcode();
        zbc.setValue(zbResultEntity.getZbCode());
        zbc.setColor("#ccccccc");

        Zbname zbn = new Zbname();
        zbn.setValue(zbResultEntity.getZbName());
        zbn.setColor("#cccccc");

        Zbvalue zbv = new Zbvalue();
        zbv.setValue(zbResultEntity.getZbValue());
        zbv.setColor("#cccccc");

        Overvalue ov = new Overvalue();

            if((zbResultEntity.getZbValue().compareTo(z.getMinValue())) == -1){
                double ovv = z.getMinValue() - zbResultEntity.getZbValue();
                ov.setValue("-"+ovv);
                ov.setColor("#cccccc");
            }else if((zbResultEntity.getZbValue().compareTo(z.getMaxValue())) == 1){
                double ovv = zbResultEntity.getZbValue() - z.getMaxValue();
                ov.setValue("+"+ovv);
                ov.setColor("#cccccc");
            }

        Data d =new Data();
        d.setZbcode(zbc);
        d.setZbname(zbn);
        d.setZbvalue(zbv);
        d.setOvervalue(ov);

        Senderror senderror = new Senderror();
        String touser = wxBindService.selectByAdminName(z.getCreator()).getFromName();
        senderror.setTouser(touser);
        senderror.setTemplate_id(info);
        senderror.setUrl(staticUrl+"/wechat/phone/index.html?zbcode="+z.getZbCode()+"&creator="+z.getCreator());
        senderror.setTopcolor("#cccccc");
        senderror.setData(d);

        return senderror;
    }

}